package io.renren.service.impl;

import com.alibaba.fastjson.JSONObject;
import io.renren.dao.*;
import io.renren.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.renren.service.SocialSecurityTransactionService;


/**
 * 社保异动管理
 * zhangheng
 */
@Service("socialSecurityTransactionService")
public class SocialSecurityTransactionServiceImpl implements SocialSecurityTransactionService {
    @Autowired
    private SocialSecurityTransactionDao socialSecurityTransactionDao;

    @Autowired
    private SocialSecurityPayDetailDao socialSecurityPayDetailDao;

    @Autowired
    private CustomContractDao customContractDao;

    @Autowired
    private CustomSettlementDao customSettlementDao;

    @Autowired
    private SocialSecurityAreaBasicDao socialSecurityAreaBasicDao;

    @Autowired
    private EmpBaseinfoDao empBaseinfoDao;

    @Autowired
    private PersonDispatchDao personDispatchDao;

    @Override
    public SocialSecurityTransactionEntity queryObject(Integer id) {
        return socialSecurityTransactionDao.queryObject(id);
    }

    @Override
    public List<Map<String, Object>> queryList(Map<String, Object> map) {
        return socialSecurityTransactionDao.queryAllRecord(map);
    }

    @Override
    public void updateStatus(JSONObject jsonObject) {
        SysUserEntity user = (SysUserEntity) jsonObject.get("user");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar ca = Calendar.getInstance();
//		String date = format.format(ca.getTime());
        String idss = jsonObject.getString("ids");
        String[] idsp = idss.substring(1, idss.length() - 1).split(",");
        String[] ids = new String[idsp.length];
        for (int i = 0; i < idsp.length; i++) {
            ids[i] = idsp[i].substring(1, idsp[i].length() - 1);
        }

        String operation = jsonObject.getString("operation");
        String type = jsonObject.getString("type");

        if ("process".equals(type)) {//申报流程
            if ("declare".equals(operation)) {
                for (String id : ids) {
                    SocialSecurityTransactionEntity trans = socialSecurityTransactionDao.queryObject(id);
                    if (trans.getProcessStatus().equals("0")) {
                        trans.setProcessStatus("1");
                        trans.setDeclareDate(ca.getTime());
                        trans.setDeclarePerson(user.getUsername());
                        socialSecurityTransactionDao.update(trans);
                    }
                }
            } else if ("unDeclare".equals(operation)) {//不申报
                //处理预申报，申报中的社保申报记录。
                for (String id : ids) {
                    SocialSecurityTransactionEntity trans = socialSecurityTransactionDao.queryObject(id);
                    /**
                     * 只有待申报和申报中的记录可以操作不申报。
                     * 如果是待申报记录，直接改申报状态为不申报(processStatus=0)
                     * 如果是申报中记录，改申报状态为待申报(processStatus=1)
                     */
                    if (trans.getProcessStatus().equals("0")) {
                        trans.setProcessStatus("4");
                        socialSecurityTransactionDao.update(trans);
                    }
                    if (trans.getProcessStatus().equals("1")) {
                        trans.setProcessStatus("0");
                        socialSecurityTransactionDao.update(trans);
                    }
                }
            } else if ("reDeclare".equals(operation)) {//重新申报
                for (String id : ids) {
                    SocialSecurityTransactionEntity trans = socialSecurityTransactionDao.queryObject(id);
                    /**
                     * 重新申报的操作只能针对已经标记为不申报的记录
                     * 同时，在对不申报的记录选中重新申报操作时，会重新生成一条待申报记录
                     * 原纪录不发生改变
                     */
                    if (trans.getProcessStatus().equals("4")) {
                        trans.setTransactionReason("重新申报");
                        trans.setDeclareDate(ca.getTime());
                        trans.setDeclarePerson(user.getUsername());
                        trans.setDeclareType("declare01");
                        trans.setProcessStatus("0");
                        trans.setConfirmStatus("0");
                        socialSecurityTransactionDao.save(trans);
                    }
                }
            } else if ("tempQuit".equals(operation)) {//临时退保
                for (String id : ids) {
                    SocialSecurityTransactionEntity trans = socialSecurityTransactionDao.queryObject(id);
                    /**
                     * 临时退保操作只能针对已申报成功的数据
                     * 操作后添加一条退保记录到待申报中
                     * 原纪录处理不管。。。待定
                     */
                    if (trans.getProcessStatus().equals("2")) {
                        trans.setTransactionReason("临时退保");
                        trans.setDeclareDate(ca.getTime());
                        trans.setDeclarePerson(user.getUsername());
                        trans.setDeclareType("declare02");
                        trans.setProcessStatus("0");
                        trans.setConfirmStatus("0");
                        socialSecurityTransactionDao.save(trans);
                    }
                }
            }
        } else if ("confirm".equals(type)) {//审核流程
            if ("firstTrial".equals(operation)) {//初审
                for (String id : ids) {
                    SocialSecurityTransactionEntity trans = socialSecurityTransactionDao.queryObject(id);
                    if (trans.getConfirmStatus().equals("0")) {
                        trans.setConfirmStatus("1");
                        trans.setTrialJudge(user.getUsername());
                        trans.setTrialDate(ca.getTime());
                        socialSecurityTransactionDao.update(trans);
                    }
                }
            } else if ("recheck".equals(operation)) {//复审
                for (String id : ids) {
                    SocialSecurityTransactionEntity trans = socialSecurityTransactionDao.queryObject(id);
                    //复审记录必须是通过初审
                    if (trans.getConfirmStatus().equals("1")) {
                        trans.setConfirmStatus("2");
                        trans.setProcessStatus("2");
                        trans.setChiefDate(ca.getTime());
                        trans.setChiefJudge(user.getUsername());
                        socialSecurityTransactionDao.update(trans);
                        /**
                         * 申报类型(0:申保;1:退保)
                         */
                        if (trans.getDeclareType().equals("declare01")) {
                            //复审通过，要更新人员派遣表
                            PersonDispatchEntity personDispatch = personDispatchDao.queryObject(trans.getPersonDispatchId());
                            String sstype = trans.getInsuranceType();
                            if ("socialSecurity01".equals(sstype)) {//养老保险
                                personDispatch.setPension("2");//已申报
                                personDispatch.setPensionInsuredDate(ca.getTime());
                            } else if ("socialSecurity02".equals(sstype)) {//生育保险
                                personDispatch.setMaternity("2");
                                personDispatch.setMaternityInsuredDate(ca.getTime());
                            } else if ("socialSecurity03".equals(sstype)) {//工伤保险
                                personDispatch.setInjury("2");
                                personDispatch.setInjuryInsuredDate(ca.getTime());
                            } else if ("socialSecurity04".equals(sstype)) {//医疗保险
                                personDispatch.setMedicare("2");
                                personDispatch.setMedicareInsuredDate(ca.getTime());
                            } else if ("socialSecurity05".equals(sstype)) {//失业保险
                                personDispatch.setUnemployment("2");
                                personDispatch.setUnemploymentInsuredDate(ca.getTime());
                            } else if ("socialSecurity06".equals(sstype)) {//五险合一
                                personDispatch.setFiveOneInsurance("2");
                            }
                            personDispatchDao.update(personDispatch);

                            //生成社保缴付明细表数据
                            insertSocialSecurityPayDetail(trans);
                        } else {
                            //复审通过，要更新人员派遣表
                            PersonDispatchEntity personDispatch = personDispatchDao.queryObject(trans.getPersonDispatchId());
                            //添加退保状态及退保时间
                            String sstype = trans.getInsuranceType();
                            if ("socialSecurity01".equals(sstype)) {//养老保险
                                personDispatch.setPension("4");//已申报
                                personDispatch.setPensionSurrenderDate(ca.getTime());
                            } else if ("socialSecurity02".equals(sstype)) {//生育保险
                                personDispatch.setMaternity("4");
                                personDispatch.setMaternitySurrenderDate(ca.getTime());
                            } else if ("socialSecurity03".equals(sstype)) {//工伤保险
                                personDispatch.setInjury("4");
                                personDispatch.setInjurySurrenderDate(ca.getTime());
                            } else if ("socialSecurity04".equals(sstype)) {//医疗保险
                                personDispatch.setMedicare("4");
                                personDispatch.setMedicareSurrenderDate(ca.getTime());
                            } else if ("socialSecurity05".equals(sstype)) {//失业保险
                                personDispatch.setUnemployment("4");
                                personDispatch.setUnemploymentInsuredDate(ca.getTime());
                            } else if ("socialSecurity06".equals(sstype)) {//五险合一
                                personDispatch.setFiveOneInsurance("4");
                                personDispatch.setFiveOneSurrenderDate(ca.getTime());
                            }
                            personDispatchDao.update(personDispatch);

                            clearSocialSecurityPayDetail(trans);
                        }

                    }
                }
            } else if ("backTrial".equals(operation)) {//反审
                for (String id : ids) {
                    SocialSecurityTransactionEntity trans = socialSecurityTransactionDao.queryObject(id);
                    /**
                     * 反审，只针对未复审记录
                     * 改变数据状态为待申报
                     */
                    if (trans.getProcessStatus().equals("1") || trans.getConfirmStatus().equals("0") ||
                            trans.getConfirmStatus().equals("1")) {
                        trans.setTransactionReason("反审");
                        trans.setProcessStatus("0");
                        trans.setConfirmStatus("0");
                        socialSecurityTransactionDao.update(trans);
                    }
                }
            } else if ("failedCheck".equals(operation)) {//退回
                for (String id : ids) {
                    SocialSecurityTransactionEntity trans = socialSecurityTransactionDao.queryObject(id);
                    /**
                     * 退回，只针对已复审记录，即社保局申报未通过
                     * 要清空之前已经生成社保交付明细数据
                     */
                    if (trans.getConfirmStatus().equals("2")) {
                        trans.setTransactionReason("退回");
                        //trans.setProcessStatus("0");
                        trans.setConfirmStatus("4");
                        socialSecurityTransactionDao.update(trans);

                        clearSocialSecurityPayDetail(trans);
                    }
                }
            }
        }

    }

    @Override
    public int queryTotal(Map<String, Object> map) {
        return socialSecurityTransactionDao.queryTotal(map);
    }

    @Override
    public void save(SocialSecurityTransactionEntity socialSecurityTransaction) {
        socialSecurityTransactionDao.save(socialSecurityTransaction);
    }

    @Override
    public void update(SocialSecurityTransactionEntity socialSecurityTransaction) {
        socialSecurityTransactionDao.update(socialSecurityTransaction);
    }

    @Override
    public void delete(Integer id) {
        socialSecurityTransactionDao.delete(id);
    }

    @Override
    public void deleteBatch(Integer[] ids) {
        socialSecurityTransactionDao.deleteBatch(ids);
    }

    public void insertSocialSecurityPayDetail(SocialSecurityTransactionEntity trans) {
        Calendar ca = Calendar.getInstance();
        //社保缴费明细
        SocialSecurityPayDetailEntity payDetailEntity = new SocialSecurityPayDetailEntity();

        //SocialSecurityTransactionEntity trans = socialSecurityTransactionDao.queryObject(id);
        trans.setConfirmStatus("");
        trans.setProcessStatus("");

        EmpBaseinfoEntity emp = empBaseinfoDao.queryObject(trans.getEmployId());
        String settlementid = trans.getUnitId();
        //获得该社保异动记录对应的结算点记录
        CustomSettlementEntity settlementEntity = customSettlementDao.queryObject(settlementid);
        //获得结算点对应的合同记录
        //List<CustomContractEntity> contractEntity = customContractDao.getContractByContractNO(settlementEntity.getContractNo());
        //获取责任人和责任部门
        String zrr = settlementEntity.getDutyPerson();//contractEntity.get(0).getResponsibilityperson();
        String zrbm = settlementEntity.getDutyDepartment();//contractEntity.get(0).getResponsibilitydepartment();

        //此处有异议，结算点和区域基数表的关系键不能是区域基数表的主键
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("year", ca.get(Calendar.YEAR));
        map.put("index", settlementEntity.getAreaBaseId());
        List<SocialSecurityAreaBasicEntity> areaBasicList = socialSecurityAreaBasicDao.queryByIndex(map);


        payDetailEntity.setEmpid(emp.getId());
        payDetailEntity.setUnitId(settlementid);
        payDetailEntity.setResponsibilitydepartment(zrbm);
        payDetailEntity.setResponsibilityperson(zrr);
        payDetailEntity.setUnitName(settlementEntity.getSettlementName());
        payDetailEntity.setName(emp.getName());
        payDetailEntity.setCardNo(emp.getIdno());
        payDetailEntity.setYear(ca.get(Calendar.YEAR));
        payDetailEntity.setIsCarryOver(0);
        //从当前月份生产社保缴费明细一直到12月
        for (int i = 1; i <= 12; i++) {
            for (SocialSecurityAreaBasicEntity areaBasicEntity : areaBasicList) {
                if (i == Integer.valueOf(areaBasicEntity.getMonth())) {
                    if ("socialSecurity01".equals(trans.getInsuranceType())) {//养老保险
                        payDetailEntity.setSocialSecurityType("socialSecurity01");
                        payDetailEntity.setBaseNum(areaBasicEntity.getYanglbxBasic());
                        payDetailEntity.setUnitScale(areaBasicEntity.getYanglbxDwbl());
                        payDetailEntity.setPersonScale(areaBasicEntity.getYanglbxGrbl());
                        payDetailEntity.setUnitPayable(areaBasicEntity.getYanglbxBasic() * areaBasicEntity.getYanglbxDwbl());
                        payDetailEntity.setPersonPayable(areaBasicEntity.getYanglbxBasic() * areaBasicEntity.getYanglbxGrbl());
                        payDetailEntity.setPayableState("0");
                    } else if ("socialSecurity02".equals(trans.getInsuranceType())) {//生育保险
                        payDetailEntity.setSocialSecurityType("socialSecurity02");
                        payDetailEntity.setBaseNum(areaBasicEntity.getShengybxBasic());
                        payDetailEntity.setUnitScale(areaBasicEntity.getShengybxDwbl());
                        payDetailEntity.setPersonScale(areaBasicEntity.getShengybxGrbl());
                        payDetailEntity.setUnitPayable(areaBasicEntity.getShengybxBasic() * areaBasicEntity.getShengybxDwbl());
                        payDetailEntity.setPersonPayable(areaBasicEntity.getShengybxBasic() * areaBasicEntity.getShengybxGrbl());
                        payDetailEntity.setPayableState("0");
                    } else if ("socialSecurity03".equals(trans.getInsuranceType())) {//工伤保险
                        payDetailEntity.setSocialSecurityType("socialSecurity03");
                        payDetailEntity.setBaseNum(areaBasicEntity.getGongsbxBasic());
                        payDetailEntity.setUnitScale(areaBasicEntity.getGongsbxDwbl());
                        payDetailEntity.setPersonScale(areaBasicEntity.getGongsbxGrbl());
                        payDetailEntity.setUnitPayable(areaBasicEntity.getGongsbxBasic() * areaBasicEntity.getGongsbxDwbl());
                        payDetailEntity.setPersonPayable(areaBasicEntity.getGongsbxBasic() * areaBasicEntity.getGongsbxGrbl());
                        payDetailEntity.setPayableState("0");
                    } else if ("socialSecurity04".equals(trans.getInsuranceType())) {//医疗保险
                        payDetailEntity.setSocialSecurityType("socialSecurity04");
                        payDetailEntity.setBaseNum(areaBasicEntity.getYilbxBasic());
                        payDetailEntity.setUnitScale(areaBasicEntity.getYilbxDwbl());
                        payDetailEntity.setPersonScale(areaBasicEntity.getYilbxGrbl());
                        payDetailEntity.setUnitPayable(areaBasicEntity.getYilbxBasic() * areaBasicEntity.getYilbxDwbl());
                        payDetailEntity.setPersonPayable(areaBasicEntity.getYilbxBasic() * areaBasicEntity.getYilbxGrbl());
                        payDetailEntity.setPayableState("0");
                    } else if ("socialSecurity05".equals(trans.getInsuranceType())) {//失业保险
                        payDetailEntity.setSocialSecurityType("socialSecurity05");
                        payDetailEntity.setBaseNum(areaBasicEntity.getShiybxBasic());
                        payDetailEntity.setUnitScale(areaBasicEntity.getShiybxDwbl());
                        payDetailEntity.setPersonScale(areaBasicEntity.getShiybxGrbl());
                        payDetailEntity.setUnitPayable(areaBasicEntity.getShiybxBasic() * areaBasicEntity.getShiybxDwbl());
                        payDetailEntity.setPersonPayable(areaBasicEntity.getShiybxBasic() * areaBasicEntity.getShiybxGrbl());
                        payDetailEntity.setPayableState("0");
                    } else if ("socialSecurity06".equals(trans.getInsuranceType())) {//五险合一
                        payDetailEntity.setSocialSecurityType("socialSecurity06");
                        payDetailEntity.setBaseNum(areaBasicEntity.getTotalBasic());
                        payDetailEntity.setUnitScale(areaBasicEntity.getTotalDwbl());
                        payDetailEntity.setPersonScale(areaBasicEntity.getTotalGrbl());
                        payDetailEntity.setUnitPayable(areaBasicEntity.getTotalBasic() * areaBasicEntity.getTotalDwbl());
                        payDetailEntity.setPersonPayable(areaBasicEntity.getTotalBasic() * areaBasicEntity.getTotalGrbl());
                        payDetailEntity.setPayableState("0");
                    }

                    payDetailEntity.setMonth(i);
                    socialSecurityPayDetailDao.saveByDynamicCol(payDetailEntity);
                    break;
                }
            }
        }
    }

    public void clearSocialSecurityPayDetail(SocialSecurityTransactionEntity trans) {
        Calendar ca = Calendar.getInstance();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("year", ca.get(Calendar.YEAR));
        map.put("type", trans.getDeclareType());
        map.put("month", ca.get(Calendar.MONTH) + 1);
        map.put("empid", trans.getEmployId());
        List<SocialSecurityPayDetailEntity> payDetailEntityList = socialSecurityPayDetailDao.getSingleTypeList(map);

        for (SocialSecurityPayDetailEntity payDetailEntity : payDetailEntityList) {
            if ("socialSecurity01".equals(trans.getInsuranceType())) {//养老保险
                payDetailEntity.setSocialSecurityType("socialSecurity01");
                payDetailEntity.setBaseNum(0d);
                payDetailEntity.setUnitScale(0d);
                payDetailEntity.setPersonScale(0d);
                payDetailEntity.setUnitPayable(0d);
                payDetailEntity.setPersonPayable(0d);
                payDetailEntity.setPayableState("0");
            } else if ("socialSecurity02".equals(trans.getInsuranceType())) {//生育保险
                payDetailEntity.setSocialSecurityType("socialSecurity02");
                payDetailEntity.setBaseNum(0d);
                payDetailEntity.setUnitScale(0d);
                payDetailEntity.setPersonScale(0d);
                payDetailEntity.setUnitPayable(0d);
                payDetailEntity.setPersonPayable(0d);
                payDetailEntity.setPayableState("0");
            } else if ("socialSecurity03".equals(trans.getInsuranceType())) {//工伤保险
                payDetailEntity.setSocialSecurityType("socialSecurity03");
                payDetailEntity.setBaseNum(0d);
                payDetailEntity.setUnitScale(0d);
                payDetailEntity.setPersonScale(0d);
                payDetailEntity.setUnitPayable(0d);
                payDetailEntity.setPersonPayable(0d);
                payDetailEntity.setPayableState("0");
            } else if ("socialSecurity04".equals(trans.getInsuranceType())) {//医疗保险
                payDetailEntity.setSocialSecurityType("socialSecurity04");
                payDetailEntity.setBaseNum(0d);
                payDetailEntity.setUnitScale(0d);
                payDetailEntity.setPersonScale(0d);
                payDetailEntity.setUnitPayable(0d);
                payDetailEntity.setPersonPayable(0d);
                payDetailEntity.setPayableState("0");
            } else if ("socialSecurity05".equals(trans.getInsuranceType())) {//失业保险
                payDetailEntity.setSocialSecurityType("socialSecurity05");
                payDetailEntity.setBaseNum(0d);
                payDetailEntity.setUnitScale(0d);
                payDetailEntity.setPersonScale(0d);
                payDetailEntity.setUnitPayable(0d);
                payDetailEntity.setPersonPayable(0d);
                payDetailEntity.setPayableState("0");
            } else if ("socialSecurity06".equals(trans.getInsuranceType())) {//五险合一
                payDetailEntity.setSocialSecurityType("socialSecurity06");
                payDetailEntity.setBaseNum(0d);
                payDetailEntity.setUnitScale(0d);
                payDetailEntity.setPersonScale(0d);
                payDetailEntity.setUnitPayable(0d);
                payDetailEntity.setPersonPayable(0d);
                payDetailEntity.setPayableState("0");

                socialSecurityPayDetailDao.update(payDetailEntity);

            }
        }
    }

}
